# =============================================================================
# APPENDIX O FIGURE 19A: TENURE ANALYSIS BY POWER-SHARING QUARTILE
# Mean tenure of leaders by legislative power-sharing quartile
# =============================================================================

# --- PACKAGES ----------------------------------------------------------------
library(tidyverse)
library(matrixStats)
library(haven)
library(dplyr)
library(ggplot2)

# --- DATA LOADING ------------------------------------------------------------
data <- read_dta("leader_tvc_2.dta", encoding = "latin1") %>%
  mutate(COWcode = ccode)
latent <- read.csv("estimates_independent.csv")

# --- DATA PREPARATION --------------------------------------------------------
# Merge and create leader summaries
df_summary <- data %>%
  left_join(latent, by = c("COWcode", "year")) %>%
  filter(legislature == 1 & !is.na(dyn.estimates)) %>%
  group_by(leadid) %>%
  summarize(
    tenure = max(time, na.rm = TRUE),
    coup_exit = as.numeric(any(exit == "revolt")),
    dyn_est = first(dyn.estimates),
    .groups = "drop"
  ) %>%
  mutate(dyn_quartile = ntile(dyn_est, 4))

# Create summary statistics table
summary_table <- df_summary %>%
  group_by(dyn_quartile) %>%
  summarize(
    `Number of Leaders` = n(),
    `Mean Tenure (Years)` = round(mean(tenure, na.rm = TRUE), 1),
    `Median Tenure (Years)` = round(median(tenure, na.rm = TRUE), 1),
    `Coup Exit Rate` = round(mean(coup_exit, na.rm = TRUE), 2),
    .groups = "drop"
  )

print(summary_table)

# Create plotting dataframe
summary_df <- data.frame(
  Quartile = factor(c("Quartile 1", "Quartile 2", "Quartile 3", "Quartile 4"),
                    levels = c("Quartile 1", "Quartile 2", "Quartile 3", "Quartile 4")),
  Mean_Tenure = c(11.4, 7.5, 7.7, 7.3)
)

# --- VISUALIZATION -----------------------------------------------------------
p_tenure <- ggplot(summary_df, aes(x = Quartile, y = Mean_Tenure)) +
  geom_bar(stat = "identity", fill = "gray70", color = "black") +
  geom_text(aes(label = Mean_Tenure), vjust = -0.5, size = 4) +
  labs(
    title = "",
    x = "Latent Power-Sharing Quartile",
    y = "Mean Tenure (Years)"
  ) +
  theme_minimal() +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank()
  )

# --- OUTPUT ------------------------------------------------------------------
ggsave("tenure.pdf", plot = p_tenure, width = 8, height = 6)